<?php

namespace App\Admin\Forms;

use App\Models\VideoCategory;
use App\Models\Video;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;

class ImportVideoForm extends Form 
{


    // 处理请求
    public function handle(array $input)
    {
        
        $state = $input['state'] ?? 1;
        $is_recommend = $input['is_recommend'] ?? 0;
        $category_id = $input['category_id'] ?? 0;
        
        $videos = $input['videos'] ;
        // 从文件中读取数据到PHP变量 
        if($videos){
            $file = storage_path('app/public/images/admin/').$videos;
            $json_string = file_get_contents($file); 
            // 用参数true把JSON字符串强制转成PHP数组 
            $data = json_decode($json_string, true);
            try{
                DB::beginTransaction();
                foreach ($data as $key => $value) {
                    if(Video::where('title',$value['title'])->exists()){
                        continue;
                    }
                    $item = [
                        'title'=>$value['title']??$value['name'],
                        'face_img'=>$value['face_img']??$value['pic'],
                        'url'=>$value['url']??$value['m3u8'],
                        'category_id'=>$category_id,
                        'is_recommend'=>$is_recommend,
                        'state'=>$state,
    
                    ];
                    Video::create($item);
                }
                DB::commit();
            }catch(\Exception $e){
                \Log::error($e->getMessage());
                DB::rollBack();
                return $this->response()->alert(true)->error('检查文件格式是否正确')->detail($e->getMessage());
            }
            
        }
        
        
        $res['state'] = true;
        $res['msg'] = "";
        if($res['state']==false){
            return $this->response()->error($res['msg'])->refresh();
        }
        else{
            return $this->response()->success('上传成功')->refresh();
        }
        
    }

    public function form()
    {
        $this->select('category_id','视频分类')->options(VideoCategory::show()->pluck('name','id'))->required();
        $this->switch('state','是否显示')->default(1);
        $this->switch('is_recommend','是否推荐')->default(0);
        $this->file('videos','json文件')->uniqueName()->autoUpload()->help('json文件格式：[
            {
              "name": "视频名称",
              "pic": "图片路径",
              "m3u8": "m3u8路径"
            },
            {
                "name": "视频名称",
                "pic": "图片路径",
                "m3u8": "m3u8路径"
              }
          ]');
    }

    // 返回表单数据，如不需要可以删除此方法
    public function default()
    {
        return [
            'state'  => 1,
            'is_recommend' => 0,
        ];
    }
}